package com.acwing.partition9;

import java.io.*;

/**
 * @author `RKC`
 * @date 2021/12/1 10:16
 */
public class AC849Dijkstra求最短路I {

    private static final int INF = 0x3f3f3f3f;

    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
        String[] s = reader.readLine().split(" ");
        int n = Integer.parseInt(s[0]), m = Integer.parseInt(s[1]);
        int[][] edges = new int[m][3];
        for (int i = 0; i < m; i++) {
            s = reader.readLine().split(" ");
            int x = Integer.parseInt(s[0]), y = Integer.parseInt(s[1]), z = Integer.parseInt(s[2]);
            edges[i][0] = x;
            edges[i][1] = y;
            edges[i][2] = z;
        }
        int ans = dijkstra(n, edges, 1, n);
        writer.write(ans + "\n");
        writer.flush();
    }

    private static int dijkstra(int n, int[][] edges, int start, int end) {
        //稠密图使用邻接矩阵构建图
        int[][] matrix = new int[n + 1][n + 1];
        int[] distance = new int[n + 1];
        boolean[] visited = new boolean[n + 1];
        for (int i = 1; i <= n; i++) {
            distance[i] = INF;
            for (int j = 1; j <= n; j++) matrix[i][j] = INF;
        }
        distance[start] = 0;

        for (int[] edge : edges) matrix[edge[0]][edge[1]] = Math.min(edge[2], matrix[edge[0]][edge[1]]);
        for (int k = 0; k < n; k++) {
            //每一次找出当前距离起点最近且没有被选出来过的点
            int u = -1;
            for (int i = 1; i <= n; i++) {
                if (!visited[i] && (u == -1 || (distance[u] > distance[i]))) u = i;
            }
            //更新以u为中转点，到其它点的距离
            if (u == end) break;
            visited[u] = true;
            for (int v = 1; v <= n; v++) {
                distance[v] = Math.min(distance[v], distance[u] + matrix[u][v]);
            }
        }
        return distance[end] == INF ? -1 : distance[end];
    }
}
